package sm.div.main;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sm.dam.api.DBDictService;
import sm.dbdict.def.DBDict;
import sm.hibernate.HibernateMappingUtil;

public class GenerateHBMMain {
	private static Logger logger = LoggerFactory
			.getLogger(GenerateHBMMain.class);

	public static void main(String[] args) throws Exception {
		String[] contexts = new String[] { "context" };
		int argsLength = args.length;
		if (argsLength == 1) {
			String context = args[0].trim();
			contexts = new String[] { context };
		}

		for (String context : contexts) {
			if (logger.isDebugEnabled()) {
				logger.debug("Generate hibernate mapping file for context "
						+ context);
			}

			SessionFactory sessionFactory = new Configuration()
					.configure(context + ".cfg.xml")
					.addResource(context + "/dbdict.hbm.xml")
					.buildSessionFactory();
			Session session = sessionFactory.openSession();

			Query query = session
					.createQuery("from dbdict where name != :name");
			query.setString("name", DBDictService.DBDICT);
			List<Object> list = (List<Object>) query.list();
			for (Object obj : list) {
				Map<String, Object> result = (Map<String, Object>) obj;
				String name = (String) result.get("name");
				DBDict dbdict = (DBDict) result.get("descriptor");

				if (logger.isDebugEnabled()) {
					logger.debug("Generate hibernate mapping file for dbdict "
							+ name);
				}

				Document hbm = HibernateMappingUtil.generateHBM(dbdict);

				File dir = new File(GenerateHBMMain.class.getClassLoader()
						.getResource(context).toURI());
				File newHbmFile = new File(dir, name + ".hbm.xml");
				if (newHbmFile.exists()) {
					newHbmFile.delete();
				}
				newHbmFile.createNewFile();
				FileOutputStream os = new FileOutputStream(newHbmFile);
				OutputFormat of = OutputFormat.createPrettyPrint();
				XMLWriter writer = new XMLWriter(os, of);
				writer.write(hbm);
			}
			session.close();
		}
	}
}
